import bpy
from bpy.types import Operator
import math
import bmesh
from mathutils import Matrix,Vector

class Draw_Cube_Op(Operator):
    bl_idname = "object.draw_cube"
    bl_label = "draw cube"
    bl_description = "draw a cube"

    # Origin point transformation settings
    mesh_offset = (0, 0, 0)
    origin_offset = (0, 0, 0)

    def vert(self,x,y,z):
        return (x + self.origin_offset[0], y + self.origin_offset[1], z + self.origin_offset[2])

    def execute(self,context):
        name = 'Cubert'

        verts = [self.vert(1.0, 1.0, -1.0),
                self.vert(1.0, -1.0, -1.0),
                self.vert(-1.0, -1.0, -1.0),
                self.vert(-1.0, 1.0, -1.0),
                self.vert(1.0, 1.0, 1.0),
                self.vert(1.0, -1.0, 1.0),
                self.vert(-1.0, -1.0, 1.0),
                self.vert(-1.0, 1.0, 1.0)]

        faces = [(0, 1, 2, 3),
                (4, 7, 6, 5),
                (0, 4, 5, 1),
                (1, 5, 6, 2),
                (2, 6, 7, 3),
                (4, 0, 3, 7)]

        mesh = bpy.data.meshes.new(name)
        mesh.from_pydata(verts, [], faces)

        obj = bpy.data.objects.new(name, mesh)
        bpy.context.scene.collection.objects.link(obj)

        bpy.context.view_layer.objects.active = obj
        obj.select_set(True)

        scale_matrix = Matrix.Scale(2, 4, (0, 0, 1)) # Scale by 2 on Z
        obj.matrix_world @= scale_matrix

        translation_matrix = Matrix.Translation((0,0,0))
        scale_matrix = Matrix.Scale(10, 4, (0,0,1)) # (伸缩倍数，几维矩阵(三维一般就是4维)，伸缩的轴)
        rotation_mat = Matrix.Rotation(math.radians(45), 4, (1,1,0)) #（旋转的角度（弧度），几维矩阵（三维一般是4维），绕哪个轴旋转） 

        obj.matrix_world @= translation_matrix @ rotation_mat @ scale_matrix # 使用总矩阵移动

        # obj.data.transform(Matrix.Translation((0,0,10))) # 注意，使用的是实体坐标,单独移动
                
        return {'FINISHED'}


class Draw_BCube_Op(Operator):
    bl_idname = "object.draw_cube"
    bl_label = "draw cube"
    bl_description = "draw a cube"
    
    def execute(self,context):
        # Create separate matrix for each transformation.
        translate = Matrix.Translation(Vector((0.5, -0.25, 0.25)))

        # Rotate 45 degrees around the z axis, (0.0, 0.0, 1.0).
        rotate = Matrix.Rotation(math.pi / 4.0, 4, Vector((0.0, 0.0, 1.0)))

        # Use a 4D vector to create a 4 x 4 nonuniform scale.
        scale = Matrix.Diagonal(Vector((1.0, 0.5, 0.75, 1.0)))

        # Composite affine transform from three separate matrices
        # with the matmul operator (the at symbol, '@').
        transform = translate @ rotate @ scale

        bm = bmesh.new()
        bmesh.ops.create_cube(bm, size=0.5, matrix=transform, calc_uvs=True)
        mesh_data = bpy.data.meshes.new("Cube")
        bm.to_mesh(mesh_data)
        bm.free()
        mesh_obj = bpy.data.objects.new(mesh_data.name, mesh_data)
        bpy.context.collection.objects.link(mesh_obj)
        
        return {'FINISHED'}